﻿using System;
using System.Data.Common;
// Krzysztof Heim
// pktools.codeplex.com

namespace PKTools.Database
{
    public abstract class SqlStampedObject : SqlObject
    {
        protected int
            __stamp;

        protected abstract string __StampCode { get; }

        protected override void LoadRecordStamp(DbDataReader reader)
        {
            object
                temp = reader[this.__StampCode];

            this.__stamp = temp == DBNull.Value ? 0 : (int)temp;
        }

        protected override string SetupSetQuery(string setQuery)
        {
            return setQuery + this.__StampCode + "=" + this.__StampCode + "+1";
        }

        protected override string SetupPKQuery(Sql sql, string pkQuery, bool validateStamp)
        {
            if (!validateStamp)
                return base.SetupPKQuery(sql, pkQuery, false);

            sql.AddInput("__Stamp", this.__stamp);
            return pkQuery + this.__StampCode + "=@__Stamp";
        }

        protected override void AfterUpdate()
        {
            ++this.__stamp;
        }

        protected override string RecordNotFoundText
        {
            get { return string.Format("record not found or has been changed (stamp = {0})", this.__stamp); }
        }
    }
}